<script setup lang="ts" name="building-list">
import AMapLoader from "@amap/amap-jsapi-loader";
import {
useReformInstallationProjectBuildingList,
useReformInstallationProjectBuildingSave,
} from "@fl/api/elevator-api";
import { SearchTable, SubmitBtn } from "@fl/components";
import { useMessage } from "@fl/hooks/web/use-message";
import { useUserStoreWithOut } from "@fl/store/modules/user";
import { hasPermi } from "@fl/utils/has-permi";
import { cloneDeep } from "lodash-es";
import type { PlusColumn, PlusDialog } from "plus-pro-components";
import { useRoute, useRouter } from "vue-router";
import type { VxeGridProps, VxePagerEvents } from "vxe-table";
const router = useRouter();
const userStore = useUserStoreWithOut();
const areaCode = userStore.getOrgInfo?.areaCode ?? "";
const isZone = ref<boolean>(areaCode==='429006000000');

const { createConfirmModal } = useMessage();
const route = useRoute();
const { go } = useRouter();
const projectName = route.query.projectName as string | undefined;
const id = route.query.id as string | undefined;
const initForm = {
    projectName: "",
    building: "",
    address: "",
    longitude: "",
    latitude: "",
    map: "",
    id: "",
    natureNo: "",
    simpleNo: "",
};
const form = ref(cloneDeep(initForm));
const initialState = {
    projectId: id || "",
    projectName: projectName || "",
};
const visible = ref(false);

const state = ref(cloneDeep(initialState));
const tablePage = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0,
});
const params = computed(() => ({
    ...state.value,
    pageIndex: tablePage.currentPage,
    pageSize: tablePage.pageSize,
    orderBy: "create_time", // 根据创建时间排序
    orderType: "desc", // 降序
}));
const { data, isLoading } = useReformInstallationProjectBuildingList(params);
const records = ref<any>();

const handlePageChange: VxePagerEvents.PageChange = ({ currentPage, pageSize }) => {
    tablePage.currentPage = currentPage;
    tablePage.pageSize = pageSize;
};
watchEffect(() => {
    if (data.value) {
        records.value = cloneDeep(data.value.records);
        tablePage.total = data.value.total!;
    }
});

const columns: PlusColumn[] = [
    {
        colProps: {
            span: 8,
        },
        label: "小区名称",
        prop: "projectName",
        fieldProps: {
            disabled: true,
        },
    },
];
const gridOptions = reactive<VxeGridProps>({
    columns: [
        { title: "序号", type: "seq", width: 60 },
        { field: "building", title: "楼栋" },
        { field: "address", title: "楼栋地址" },
        { field: "natureNo", title: "自然栋号" },
        { field: "simpleNo", title: "栋号" },
        { field: "longitude", title: "经度" },
        { field: "latitude", title: "纬度" },
        { field: "unitNum", title: "单元数量" ,visible:!isZone.value},
        { slots: { default: "operate" }, title: "操作", width: 250 },
    ],
});

const formRef = ref();
function goBack() {
    go(-1);
}
watch(
    () => visible.value,
    () => {
        if (visible.value) {
            initMap();
            form.value.projectName = projectName || "";
        }
    }
);
function cancel() {
    createConfirmModal({
        title: "提示",
        content: "您是否确定要放弃当前已编辑或输入的信息?",
        onSuccess: () => {
            reset();
        },
    });
}

function reset() {
    form.value = cloneDeep(initForm);
    visible.value = false;
}

const rules = {
    projectName: [{ required: true, message: "请输入小区名称", trigger: "blur" }],
    building: [{ required: true, message: "请输入楼栋", trigger: "blur" }],
    natureNo: [{ required: true, message: "请输入自然栋号", trigger: "blur" }],
    address: [{ required: true, message: "请输入楼栋地址", trigger: "blur" }],
    longitude: [{ required: true, message: "请输入经度", trigger: "blur" }],
    latitude: [{ required: true, message: "请输入纬度", trigger: "blur" }],
};

/**
 * 地图处理
 */
const showSearchList = ref(false);
window._AMapSecurityConfig = {
    securityJsCode: "3d2b0d182274c8f36d175015792a5525",
};
function openInfoWindow() {
    const infoWindow = new AMap.InfoWindow({
        // anchor: 'top-right', //信息窗体的三角所在位置
        content: `<h3 style="font-weight: bold;line-height: 32px">${
            form.value.address
        }</h3><h4>经度${
            form.value && form.value.longitude ? form.value.longitude : ""
        }，纬度${form.value && form.value.latitude ? form.value.latitude : ""}</h4>`, // 信息窗体的内容可以是任意html片段
        // 创建信息窗体
        isCustom: false, // 使用自定义窗体
        offset: new AMap.Pixel(0, 0),
    });
    infoWindow.open(map, [
        form.value && form.value.longitude ? form.value.longitude : "",
        form.value && form.value.latitude ? form.value.latitude : "",
    ]); // 填写想要窗体信息指示的坐标
}
let map: any = null; // 初始化地图
function initMap() {
    const markers = [];

    AMapLoader.load({
        key: "8e125d7a61c3c334ca9538a5c6798582", // 申请好的Web端开发者Key，首次调用 load 时必填
        plugins: [
            "AMap.Geocoder",
            "AMap.PlaceSearch",
            "AMap.Scale", // 工具条，控制地图的缩放、平移等
            "AMap.ToolBar", // 比例尺，显示当前地图中心的比例尺
            "AMap.Geolocation", // 定位，提供了获取用户当前准确位置、所在城市的方法
            "AMap.HawkEye", // 鹰眼，显示缩略图
        ], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
        version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
    })
        .then((AMap) => {
            map = new AMap.Map("mapBox", {
                center: [
                    form.value && form.value.longitude
                        ? form.value.longitude
                        : "114.305215",
                    form.value && form.value.latitude ? form.value.latitude : "30.592935",
                ], // 初始化地图中心点位置
                doubleClickZoom: true, // 双击放大缩小
                dragEnable: true, // 禁止鼠标拖拽
                keyboardEnable: true, // 键盘控制放大缩小移动旋转
                scrollWheel: true, // 鼠标滚轮放大缩小
                viewMode: "3D", // 是否为3D地图模式
                // 设置地图容器id
                zoom: title.value === "新增" ? 16 : 28, // 初始化地图层级
            });
            map.setDefaultCursor("pointer"); // 使用CSS默认样式定义地图上的鼠标样式（default/pointer/move/crosshair）
            map.addControl(new AMap.Scale()); // 异步同时加载多个插件
            map.addControl(new AMap.ToolBar());

            if (form.value.longitude && form.value.latitude) {
                const marker = new AMap.Marker({
                    position: new AMap.LngLat(form.value.longitude, form.value.latitude), // 经纬度对象，也可以是经纬度构成的一维数组[lng, lat]
                });
                marker.on("click", (e) => {
                    openInfoWindow();
                });
                markers.push(marker); // 将marker标注用markers数组存起来，便于移除上次点击地图产生的点标记

                // 将创建的点标记添加到已有的地图实例：
                map.add(marker);
                // map.add(marker);
            }

            // 显示地图层级与中心点信息
            function logMapinfo() {
                const zoom = map.getZoom(); // 获取当前地图级别
                const center = map.getCenter(); // 获取当前地图中心位置
            }
            // 绑定地图移动与缩放事件
            map.on("moveend", logMapinfo);
            map.on("zoomend", logMapinfo);

            // 为地图注册click事件获取鼠标点击出的经纬度坐标
            map.on("click", (e: any) => {
                if (title.value === "查看") return;
                map.remove(markers); // 移除地图上已创建的点标记
                form.value.longitude = e.lnglat.getLng();
                form.value.latitude = e.lnglat.getLat();

                const marker = new AMap.Marker({
                    position: new AMap.LngLat(form.value.longitude, form.value.latitude),
                    title: "当前选中的楼栋",
                });
                markers.push(marker); // 将marker标注用markers数组存起来，便于移除上次点击地图产生的点标记

                map.add(marker);
            });
        })
        .catch((e) => {
            console.log(e);
        });
}

// 搜索
function onPlaceSearch() {
    showSearchList.value = true;
    console.log(map);
    const placeSearch = new AMap.PlaceSearch({
        autoFitView: true, // 是否自动调整地图视野使绘制的 Marker 点都处于视口的可见范围
        citylimit: true, //是否强制限制在设置的城市内搜索
        map, // 展现结果的地图实例
        city: "武汉", //兴趣点城市
        pageIndex: 1, // 页码
        pageSize: 6, // 单页显示结果条数
        panel: "search-list-box", // 结果列表将在此容器中进行展示。
    });
    placeSearch.search(form.value.address, (status: any, result: any) => {
        console.log("status", status);
        console.log("placeSearch", result);
        if (form.value.id) {
            //showSearchList.value = false
            //openInfoWindow()
        }
    });

    placeSearch.on("listElementClick", (e: any) => {
        console.log("onListElementClick", e);
        form.value.longitude = e.data.location.lng;
        form.value.latitude = e.data.location.lat;
        showSearchList.value = false;
        // this.poi = e.data
    });
    placeSearch.on("markerClick", (e: any) => {
        console.log("onMarkerClick", e);
        // this.poi = e.data
        form.value.longitude = e.data.location.lng;
        form.value.latitude = e.data.location.lat;
        showSearchList.value = false;
        /*
     adname ：行政区
     location: 经纬度 lng,lat
     name： 标题
     address：地址
     */
    });
}
function onBlur() {
    if (form.value.longitude && form.value.latitude) {
        console.log([form.value.longitude, form.value.latitude]);
        initMap();
        // const marker = new AMap.Marker({
        //   position: [form.value.longitude, form.value.latitude],
        //   title: "当前选中的楼栋",
        // });
        // map.add(marker);
    }
}
const { mutate, isPending } = useReformInstallationProjectBuildingSave();
function submit() {
    formRef.value.validate((valid) => {
        let params = {
            ...form.value,
            projectId: id,
        };
        if (valid) {
            createConfirmModal({
                title: "保存",
                content: "确定保存吗？",
                onSuccess: () => {
                    mutate(params, {
                        onSuccess: () => {
                            ElMessage.success("保存成功");
                            reset();
                        },
                    });
                },
            });
        }
    });
}
const title = ref("新增");
function showDialog(type: string, row?: any) {
    if (type === "detail" || type === "edit") {
        title.value = type === "detail" ? "查看" : "编辑";
        form.value = cloneDeep(row);
        console.log(form.value);
        visible.value = true;
    } else {
        title.value = "新增";
        visible.value = true;
    }
}
function toUnit(row) {
    router.push({
        name: "unit-list",
        query: {
            buildingId: row.id,
            projectName: projectName,
            buildingName: row.building,
            natureNo: row.natureNo,
        },
    });
}
</script>
<template>
    <ElCard shadow="never">
        <el-button @click="goBack"> 返回列表 </el-button>

        <ElSkeleton v-if="isLoading" animated class="mt-20" />
        <template v-else>
            <div class="mt-20">
                <PlusForm
                    v-model="state"
                    :columns="columns"
                    :label-width="100"
                    :has-footer="false"
                />
            </div>
            <SearchTable
                v-bind="gridOptions"
                :loading="isLoading"
                :data="records"
                @page-change="handlePageChange"
                v-model:pager="tablePage"
            >
                <template #toolbar_buttons>
                    <ElButton
                        type="primary"
                        @click="showDialog('add')"
                        v-if="hasPermi('清册数据-新增楼栋')"
                        >新增</ElButton
                    >
                </template>
                <template #operate="{ row }">
                    <ElButton
                        text
                        type="primary"
                        @click="showDialog('edit', row)"
                        v-if="hasPermi('清册数据-新增楼栋')"
                        >编辑</ElButton
                    >
                    <ElButton text @click="showDialog('detail', row)">查看</ElButton>
                    <ElButton
                        v-if="hasPermi('清册数据-新增楼栋')"
                        text
                        @click="toUnit(row)"
                        >单元管理</ElButton
                    >
                </template>
            </SearchTable>
        </template>
    </ElCard>
    <PlusDialog
        v-model="visible"
        :title="title"
        width="1000"
        close-on-press-escape
        :has-footer="false"
        @closed="reset"
    >
        <template v-if="title != '查看'">
            <div class="formBox">
                <el-form ref="formRef" :model="form" label-width="auto" :rules="rules">
                    <el-row :gutter="40">
                        <el-col :span="24">
                            <el-form-item label="小区名称" prop="projectName">
                                <el-input
                                    v-model="form.projectName"
                                    placeholder="请输入小区名称"
                                    :disabled="true"
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item label="楼栋" prop="building">
                                <el-input
                                    v-model="form.building"
                                    placeholder="请输入楼栋名称"
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="自然栋栋号" prop="natureNo">
                                <el-input
                                    v-model="form.natureNo"
                                    placeholder="请输入自然栋栋号"
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="栋号" prop="simpleNo">
                                <el-input
                                    v-model="form.simpleNo"
                                    placeholder="请输入栋号"
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item
                                label=""
                                label-width="80"
                                prop="address"
                                style="
                                    color: cadetblue;
                                    font-size: 15px;
                                    font-weight: bold;
                                "
                                >使用指引:&nbsp;输入楼栋地址，点击查找按钮或按回车键来获取地址列表，用户点击选择地址列表某项，获取经纬度填入。</el-form-item
                            >
                            <el-form-item label="楼栋地址" prop="address">
                                <el-input
                                    v-model="form.address"
                                    @keyup.enter="onPlaceSearch"
                                    placeholder="请输入楼栋地址"
                                    style="width: 80%"
                                />
                                <el-button type="primary" ml20 @click="onPlaceSearch"
                                    >查找</el-button
                                >
                            </el-form-item>
                        </el-col>
                        <el-col :span="24" v-if="showSearchList">
                            <div id="search-list-box" class="search-list-box" />
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="经度" prop="longitude">
                                <el-input
                                    v-model="form.longitude"
                                    @blur="onBlur"
                                    placeholder="请输入经度"
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="纬度" prop="latitude">
                                <el-input
                                    v-model="form.latitude"
                                    @blur="onBlur"
                                    placeholder="请输入纬度"
                                />
                            </el-form-item>
                        </el-col>

                        <el-col :span="24">
                            <el-form-item label="地图">
                                <div
                                    id="mapBox"
                                    style="
                                        border: 1px solid #ddd;
                                        width: 80%;
                                        height: 350px;
                                    "
                                ></div>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </div>
            <div class="mx-auto mt20 flex justify-center">
                <el-button @click="cancel"> 取消 </el-button>

                <SubmitBtn type="primary" :loading="isPending" @click="submit">
                    保存
                </SubmitBtn>
            </div>
        </template>
        <template v-else>
            <div class="formBox">
                <el-form :model="form" label-width="auto">
                    <el-row :gutter="40">
                        <el-col :span="24">
                            <el-form-item label="小区名称:" prop="projectName">
                                {{ form.projectName || "" }}
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item label="楼栋:" prop="building">
                                {{ form.building || "" }}
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="自然栋栋号:" prop="natureNo">
                                {{ form.natureNo || "" }}
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="栋号:" prop="simpleNo">
                                {{ form.simpleNo || "" }}
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item label="楼栋地址:" prop="address">
                                {{ form.address || "" }}
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="经度:" prop="longitude">
                                {{ form.longitude || "" }}
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="纬度:" prop="latitude">
                                {{ form.latitude || "" }}
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item label="地图:">
                                <div
                                    id="mapBox"
                                    style="
                                        border: 1px solid #ddd;
                                        width: 80%;
                                        height: 500px;
                                    "
                                ></div>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </div>
        </template>
    </PlusDialog>
</template>
<style lang="scss" scoped>
.formBox {
    height: 500px;
    overflow-y: auto;
    overflow-x: hidden;
    padding-right: 8px;
    width: 100%;
    &::-webkit-scrollbar {
        width: 4px;
    }

    /* 自定义滚动条的滑块（thumb） */
    &::-webkit-scrollbar-thumb {
        background: #dcdfe6;
        border-radius: 2px;
    }
}
</style>
